package com.hqj.converter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;

/**
 * 把前端提交的数据与后台响应的数据
 * 经过封装为json数据流
 */
public class HttpMsgConverter extends AbstractHttpMessageConverter<Object> {
    /**
     * 是否允许使用
     * @param clazz
     * @return
     */
    protected boolean supports(Class<?> clazz) {
        return true;
    }

    /**
     * 获取前端的数据
     * @param clazz
     * @param inputMessage
     * @return
     * @throws IOException
     * @throws HttpMessageNotReadableException
     */
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    /**
     * 响应数据到前端
     * @param o
     * @param outputMessage
     * @throws IOException
     * @throws HttpMessageNotWritableException
     */
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

        //获取输出流
        OutputStream out = outputMessage.getBody();
        byte[] bs = JSON.toJSONBytes(o, SerializerFeature.WriteDateUseDateFormat);
        out.write(bs);

    }
}
